package cn.parus.service.Impl;

import cn.parus.common.Execption.CustomException;
import cn.parus.entity.FileShareLink;
import cn.parus.entity.FileSharing;
import cn.parus.mapper.FileSharingMapper;
import cn.parus.service.FileReceviceService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author: Axel
 * @Description: TODO
 **/
@Service
public class FileReceviceServiceImpl extends ServiceImpl<FileSharingMapper, FileSharing> implements FileReceviceService {

    @Override
    public Page<FileSharing> searchAllFileRecevier(String ownerId, Integer current, Integer size) {
        // 参数校验：ownerId 必须存在
        if (StringUtils.isBlank(ownerId)) {
            throw new CustomException("查询文件共享时，用户ID不能为空");
        }

        // 构造查询：只查询当前用户的共享记录
        Page<FileSharing> page = new Page<>(current, size);
        LambdaQueryWrapper<FileSharing> queryWrapper = new LambdaQueryWrapper<FileSharing>()
                .eq(FileSharing::getSharedWith, ownerId);  // 按文件接收者过滤

        return baseMapper.selectPage(page, queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteFileShareReceiver(String shareId) {
        if (StringUtils.isBlank(shareId)) {
            throw new CustomException("共享链接时，ID不能为空");
        }

        FileSharing existFileSharing = baseMapper.selectById(shareId);
        if(existFileSharing == null) {
            throw new CustomException("链接不存在，删除失败");
        }

        try {
            baseMapper.deleteById(shareId);
        } catch (CustomException e) {
            throw new CustomException("删除失败" + e.getMessage());
        }
    }
}
